<template>
  <div>
    <!-- 顶部面包屑标识与导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/sys-admin' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>药品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!-- 操作区域 -->
    <div style="margin: 0 0 20px 0;">
      <el-select v-model="categoryId" placeholder="请选择分类名称" style="width: 300px;"
                 @change="loadMedicineList()">
        <el-option
            v-for="item in categoryListOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-button type="primary" size="medium" style="margin-left:20px;"
                 @click="$router.push('/service/medicine/add')">添加药品
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="categoryName" label="分类名称" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="description" label="简介" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="price" label="单价" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="currentNum" label="库存" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="查看详情" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="gotoMedicineList(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" circle
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" circle
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改药品的弹出表单Dialog -->
    <el-dialog title="修改药品" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="editRules" :label-width="formLabelWidth">
        <el-form-item label="药品分类名称" prop="parentId">
          <el-select v-model="editForm.categoryId" placeholder="请选择分类名称" style="width: 300px;">
            <el-option
                v-for="item in categoryListOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="editForm.price"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="currentNum">
          <el-input v-model="editForm.currentNum"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看药品详情的弹出表单Dialog -->
    <el-dialog title="药品详情" :visible.sync="FormVisible">
      <el-form :model="editForm" :label-width="formLabelWidth">
        <el-form-item label="药品分类名称" prop="parentId">
          <el-select v-model="editForm.categoryId" style="width: 300px;" disabled="true">
            <el-option
                v-for="item in categoryListOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" readonly></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description" readonly></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="editForm.price" readonly></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="currentNum">
          <el-input v-model="editForm.currentNum" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="FormVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分页相关数据
      currentPage: this.$router.currentRoute.query.page ? parseInt(this.$router.currentRoute.query.page) : 1,
      pageSize: 20,
      pageCount: 1,
      total: 0,

      // 药品分类的下拉菜单的选项数据
      // 编辑对话框的可见性
      dialogFormVisible: false,
      FormVisible: false,
      categoryListOptions: [],
      // 药品分类ID
      categoryId: '',
      // 显示文本常量
      typeText: ['非销售药品', '销售药品'],
      inputTypeText: ['手动录入', '单选', '多选', '单选（下拉列表）', '多选（下拉列表）'],
      // 表格数据
      tableData: [],
      // 编辑表单
      editForm: {
        name: '',
        description: '',
        price: '',
        currentNum: '',
        categoryId: '',
      },
      // 编辑表单的验证规则
      editRules: {
        name: [
          {required: true, message: '请输入药品名称', trigger: 'blur'},
        ],
        description: [
          {required: true, message: '请输入描述', trigger: 'blur'},
        ],
        price: [
          {required: true, message: '请输入单价', trigger: 'blur'},
        ],
        currentNum: [
          {required: true, message: '请输入库存', trigger: 'blur'},
        ]
      },
      // 编辑表单的label宽度
      formLabelWidth: '120px'
    }
  },
  methods: {
    // 加载药品分类列表
    loadMedicinesCategoryList() {
      let url = 'http://localhost:9999/medicines-category?queryType=all';
      console.log('url = ' + url);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.categoryListOptions = jsonResult.data.list;
        } else {
          this.$message.error(jsonResult.message);
        }
      });
    },
    // 加载药品列表
    loadMedicineList() {
      let url = 'http://localhost:9999/medicines/list-by-category?categoryId=' + this.categoryId;
      console.log('url = ' + url);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          console.log("---------------------------------------------")
          console.log(this.tableData);
        } else {
          this.$message.error(jsonResult.message);
        }
      });
    },
    // 打开编辑对话框
    gotoMedicineList(medicine) {
      let url = 'http://localhost:9999/medicines/' + medicine.id;
      console.log('url = ' + url);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.FormVisible = true;
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadMedicineList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    // 打开编辑对话框
    openEditDialog(medicine) {
      let url = 'http://localhost:9999/medicines/' + medicine.id;
      console.log('url = ' + url);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadMedicineList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    // 提交编辑表单
    submitEditForm() {
      let url = 'http://localhost:9999/medicines/' + this.editForm.id + '/update';
      console.log('url = ' + url);

      let formData = this.qs.stringify(this.editForm);
      console.log('formData = ' + formData);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改药品成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadMedicineList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadMedicineList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$message.error(jsonResult.message);
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
            }
          });
        }
      });
    },
    // 打开删除确认框
    openDeleteConfirm(medicine) {
      let title = '提示';
      let message = '此操作将永久删除【' + medicine.name + '】药品, 是否继续?';
      this.$confirm(message, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(medicine);
      }).catch(() => {
      });
    },
    // 处理删除
    handleDelete(medicine) {
      let url = 'http://localhost:9999/medicines/' + medicine.id + '/delete';
      console.log('url = ' + url);

      let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
      this.axios
          .create({'headers': {'Authorization': loginInfo.token}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除药品【' + medicine.name + '】成功！',
            type: 'success'
          });
          this.loadMedicineList();
        } else {
          this.$alert(jsonResult.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadMedicineList();
            }
          });
        }
      });
    }
  },
  mounted() {
    this.loadMedicinesCategoryList();
  }
}
</script>

<style scoped>
</style>
